package sqcon.sql;

import sqcon.util.StringTokenParser;
import sqcon.util.StringParsingException;

import java.util.NoSuchElementException;

public class Table extends Aliasable {
	private String tableName;
	
	public Table(String tableName){
		super(tableName);
		this.tableName = tableName;
	}
	
	public Table(String tableName, String alias){
		super(alias);
		this.tableName = tableName;
	}
	
	public String getTableName(){
		return tableName;
	}
	
	public String toString(){
		if(this.getAlias().equals(tableName)){
			return tableName;
		}
		
		return tableName + " AS " + this.getAlias();
	}
	
	public static Table generateTable(String tableStr) 
			throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(tableStr, true);
		
		try{
			String tableName = stp.nextToken();
			String alias = stp.nextToken();
			if(alias.equalsIgnoreCase("AS")){
				alias = stp.nextToken();
			}
			if(stp.hasMoreTokens()){
				throw new ConstructSqlException("Table name parsing error");
			}
			return new Table(tableName, alias);
		}catch(StringParsingException e){
			throw new ConstructSqlException("Table name parsing error");
		}catch(NoSuchElementException nsee){
			throw new ConstructSqlException("Table name parsing error");
		}
	}
}
